<?php

namespace app\common\controller;

use think\Controller;
use think\Db;
use think\cache\driver\Redis;
use think\Exception;

class Processing extends Controller
{
    protected $time;
    protected $redis;

    public function _initialize()
    {
        parent::_initialize();
        set_time_limit(0);
        $this->time = time();
        $this->redis = new Redis();
    }


    /**
     * 获取开奖数据并执行后续操作
     */
    public function index()
    {

        echo "<br/>---------- 处理当期数据完成 ----------<br/>";
        $this->processingNew();
//        $this->processingNext();

    }
    private function processingNext(){
        echo "<br/>---------- 开始生成下期数据processingNext ----------<br/><br/>";
        $start = microtime(true);
        $data_json = file_get_contents("http://a.apiplus.net/newly.do?token=E0C5726B8E45A086&format=json&rows=1");
        $data_all = json_decode($data_json, true);
        if( $data_all && isset($data_all['data']) && !empty($data_all['data']) ){
            $data = $data_all['data'];
            //封盘时间
            $fp_list = Db::name("caipai_list")->column("id,cp_fp_time");

            $big_sql = Db::name("time")->where(['jztime'=>['>',date('H:i:s',time())]])->field("czid,min(jztime) as time")->group("czid")->buildSql();
            $small_sql = Db::name("time")->where(['jztime'=>['<=',date('H:i:s',time())]])->field("czid,max(jztime) as time")->group("czid")->buildSql();
            $begin_sql = Db::name("time")->field("czid,min(jztime) as time")->group("czid")->buildSql();
            $end_sql = Db::name("time")->field("czid,max(jztime) as time")->group("czid")->buildSql();

            $time_big = Db::name("time")->alias("a")
                ->join("{$big_sql} b","a.jztime=b.time and a.czid=b.czid","RIGHT")
                ->field("a.qihao,b.*")->buildSql();
            $time_small = Db::name("time")->alias("a")
                ->join("{$small_sql} b","a.jztime=b.time and a.czid=b.czid","RIGHT")
                ->field("a.qihao,b.*")->buildSql();
            $time_begin = Db::name("time")->alias("a")
                ->join("{$begin_sql} b","a.jztime=b.time and a.czid=b.czid","RIGHT")
                ->field("a.qihao,b.*")->buildSql();
            $time_end = Db::name("time")->alias("a")
                ->join("{$end_sql} b","a.jztime=b.time and a.czid=b.czid","RIGHT")
                ->field("a.qihao,b.*")->buildSql();

            $time_list = Db::name('caipai_list')->alias("a")
                ->join("{$time_big} b","a.id=b.czid","LEFT")
                ->join("{$time_small} c","a.id=c.czid","LEFT")
                ->join("{$time_begin} d","a.id=d.czid","LEFT")
                ->join("{$time_end} e","a.id=e.czid","LEFT")
                ->column("a.id as czid,b.qihao as big_qh,b.time as big_time,c.qihao as small_qh,c.time as small_time,d.qihao as begin_qh,d.time as begin_time,e.qihao as end_qh,e.time as end_time","a.id");

            foreach( $data as $v ){
                $code = $v['code'];
                $expect = $v['expect'];
                $opentimestamp = $v['opentimestamp'];
                $czid = 0;
                switch($code){
                    case 'cqssc':
                        //重庆时时彩
                        $czid = 1;
                        $begin_qh = $time_list[$czid]['small_qh'];
                        if( 120==intval($begin_qh) ){
                            $begin_qh = date("Ymd",strtotime("-1 day")).str_pad($begin_qh,3,"0",STR_PAD_LEFT);
                        }else{
                            $begin_qh = date('Ymd',time()).str_pad($begin_qh,3,"0",STR_PAD_LEFT);
                        }
                        if( !empty($time_list[$czid]['big_qh']) ){
                            $end_qh = date('Ymd',time()).str_pad($time_list[$czid]['big_qh'],3,"0",STR_PAD_LEFT);
                            $end_time = strtotime(date("Y-m-d",time()).' '.$time_list[$czid]['big_time']);
                        }else{
                            $end_qh = date('Ymd',time()).str_pad($time_list[$czid]['begin_qh'],3,"0",STR_PAD_LEFT);
                            $end_time = strtotime(date("Y-m-d",strtotime("+1 day")).' '.$time_list[$czid]['begin_time']);
                        }
                        $fp_time = isset($fp_list[$czid]) ? intval($fp_list[$czid]) : 0;
                        $this->insertNext($czid,$begin_qh,$end_qh,$end_time,$fp_time);
                        break;
                    case 'ahk3':
                        //安徽快三
                        $czid = 36;
                    case 'jsk3':
                        //江苏快三
                        0==$czid && $czid=44;
                    case 'tjssc':
                        //天津时时彩
                        0==$czid && $czid=8;
                        $begin_qh = !empty($time_list[$czid]['small_qh']) ? date('Ymd',time()).str_pad($time_list[$czid]['small_qh'],3,"0",STR_PAD_LEFT) : date("Ymd",strtotime("-1 day")).str_pad($time_list[$czid]['end_qh'],3,"0",STR_PAD_LEFT);
                        $end_qh = !empty($time_list[$czid]['big_qh']) ? date('Ymd',time()).str_pad($time_list[$czid]['big_qh'],3,"0",STR_PAD_LEFT) : date("Ymd",strtotime("+1 day")).str_pad($time_list[$czid]['begin_qh'],3,"0",STR_PAD_LEFT);
                        $end_time = !empty($time_list[$czid]['big_time']) ? strtotime(date("Y-m-d",time()).' '.$time_list[$czid]['big_time']) : strtotime(date("Y-m-d",strtotime("+1 day")).' '.$time_list[$czid]['begin_time']);
                        $fp_time = isset($fp_list[$czid]) ? intval($fp_list[$czid]) : 0;
                        $this->insertNext($czid,$begin_qh,$end_qh,$end_time,$fp_time);
                        break;
                    case 'bjpk10':
                        //北京赛车
                        $czid = 4;
                    case 'bjkl8':
                        //PC蛋蛋
                        0==$czid && $czid=10;
                        $begin_time = !empty($time_list[$czid]['small_time']) ? strtotime(date("Y-m-d",time()).' '.$time_list[$czid]['small_time']) : strtotime(date("Y-m-d",strtotime("-1 day")).' '.$time_list[$czid]['end_time']);
                        $end_time = !empty($time_list[$czid]['big_time']) ? strtotime(date("Y-m-d",time()).' '.$time_list[$czid]['big_time']) : strtotime(date("Y-m-d",strtotime("+1 day")).' '.$time_list[$czid]['begin_time']);
                        $fp_time = isset($fp_list[$czid]) ? intval($fp_list[$czid]) : 0;
                        if( intval($opentimestamp) > intval($begin_time) && intval($opentimestamp) < intval($end_time) ){
                            //已开奖
                            $begin_qh = $expect;
                            $end_qh = intval($expect) + 1;
                            $this->insertNext($czid,$begin_qh,$end_qh,$end_time,$fp_time);
                        }else{
                            //未开奖
                            for( $i=0; $i<=1; $i++ ){
                                $begin_qh = intval($expect) + $i;
                                $end_qh = intval($expect) + $i + 1;
                                $kjtime = 0==$i ? $begin_time : $end_time;
                                $this->insertNext($czid,$begin_qh,$end_qh,$kjtime,$fp_time);
                            }
                        }
                        break;
                    case 'gd11x5':
                        //广东11选5
                        $czid = 16;
                    case 'sd11x5':
                        //山东11选5
                        0==$czid && $czid=28;
                    case 'shssl':
                        ///上海时时乐
                        0==$czid && $czid=48;
                    case 'jx11x5':
                        //江西11选5
                        0==$czid && $czid=25;
                        $begin_qh = !empty($time_list[$czid]['small_qh']) ? date('Ymd',time()).str_pad($time_list[$czid]['small_qh'],2,"0",STR_PAD_LEFT) : date("Ymd",strtotime("-1 day")).str_pad($time_list[$czid]['end_qh'],2,"0",STR_PAD_LEFT);
                        $end_qh = !empty($time_list[$czid]['big_qh']) ? date('Ymd',time()).str_pad($time_list[$czid]['big_qh'],2,"0",STR_PAD_LEFT) : date("Ymd",strtotime("+1 day")).str_pad($time_list[$czid]['begin_qh'],2,"0",STR_PAD_LEFT);
                        $end_time = !empty($time_list[$czid]['big_time']) ? strtotime(date("Y-m-d",time()).' '.$time_list[$czid]['big_time']) : strtotime(date("Y-m-d",strtotime("+1 day")).' '.$time_list[$czid]['begin_time']);
                        $fp_time = isset($fp_list[$czid]) ? intval($fp_list[$czid]) : 0;
                        $this->insertNext($czid,$begin_qh,$end_qh,$end_time,$fp_time);
                        break;
                    case 'mlaft':
                        //幸运飞艇
                        $czid=61;
                        if( !empty($time_list[$czid]['small_qh']) ){
                            $begin_qh = $time_list[$czid]['small_qh'];
                            if( intval($begin_qh) > 131 ){
                                $begin_qh = date('Ymd',strtotime('-1 day')).$begin_qh;
                            }else{
                                $begin_qh = date('Ymd').str_pad($begin_qh,3,"0",STR_PAD_LEFT);
                            }
                        }else{
                            $begin_qh = date('Ymd',strtotime('-1 day')).$time_list[$czid]['end_qh'];
                        }
                        if( !empty($time_list[$czid]['big_qh']) ){
                            $end_qh = $time_list[$czid]['big_qh'];
                            if( intval($end_qh) > 131 ){
                                $end_qh = date('Ymd',strtotime('-1 day')).$end_qh;
                            }else{
                                $end_qh = date('Ymd').str_pad($end_qh,3,"0",STR_PAD_LEFT);
                            }
                            $end_time = strtotime(date("Y-m-d",time()).' '.$time_list[$czid]['big_time']);
                        }else{
                            $end_qh = date('Ymd').$time_list[$czid]['begin_qh'];
                            $end_time = strtotime(date("Y-m-d",strtotime("+1 day")).' '.$time_list[$czid]['begin_time']);
                        }
                        $fp_time = isset($fp_list[$czid]) ? intval($fp_list[$czid]) : 0;
                        $this->insertNext($czid,$begin_qh,$end_qh,$end_time,$fp_time);
                        break;
                    case 'pl3':
                        //排列三
                        $czid=5;
                    case 'fc3d':
                        //福彩3D
                        0==$czid && $czid=7;
                        $begin_time = !empty($time_list[$czid]['small_time']) ? strtotime(date("Y-m-d",time()).' '.$time_list[$czid]['small_time']) : strtotime(date("Y-m-d",strtotime("-1 day")).' '.$time_list[$czid]['end_time']);
                        $end_time = !empty($time_list[$czid]['big_time']) ? strtotime(date("Y-m-d",time()).' '.$time_list[$czid]['big_time']) : strtotime(date("Y-m-d",strtotime("+1 day")).' '.$time_list[$czid]['begin_time']);

                        $fp_time = isset($fp_list[$czid]) ? intval($fp_list[$czid]) : 0;
                        if( intval($opentimestamp) > intval($begin_time) && intval($opentimestamp) < intval($end_time) ){
                            //已开奖
                            $begin_qh = $expect;
                            $end_qh = intval($expect) + 1;
                            $this->insertNext($czid,$begin_qh,$end_qh,$end_time,$fp_time);
                        }else{
                            //未开奖
                            for( $i=0; $i<=1; $i++ ){
                                $begin_qh = intval($expect) + $i;
                                $end_qh = intval($expect) + $i + 1;
                                $kjtime = 0==$i ? $begin_time : $end_time;
                                $this->insertNext($czid,$begin_qh,$end_qh,$kjtime,$fp_time);
                            }
                        }
                        break;
                    case 'hk6':
                        //香港六合彩
                        $czid=9;
                    case 'qxc':
                        //七星彩
                        0==$czid && $czid=51;
                        $open_time = $time_list[$czid]['begin_time'];
                        $time_Attr = [];
                        for( $i=0; $i<=6; $i++ ){
                            $tmp_time = strtotime("-{$i} day");
                            $time_Attr[] = $this->getLowerNextTime($tmp_time,$czid,$open_time);
                        }
                        $begin_time = '';
                        $end_time = '';
                        array_map(function($v)use(&$begin_time,&$end_time){
                            if( $v > time() ){
                                $end_time = $v;
                            }elseif(empty($begin_time)){
                                $begin_time = $v;
                            }
                        },array_unique($time_Attr));

                        $fp_time = isset($fp_list[$czid]) ? intval($fp_list[$czid]) : 0;
                        if( intval($opentimestamp) > intval($begin_time) && intval($opentimestamp) < intval($end_time) ){
                            //已开奖
                            $begin_qh = $expect;
                            $end_qh = intval($expect) + 1;
                            $this->insertNext($czid,$begin_qh,$end_qh,$end_time,$fp_time);
                        }else{
                            //未开奖
                            for( $i=0; $i<=1; $i++ ){
                                $begin_qh = intval($expect) + $i;
                                $end_qh = intval($expect) + $i + 1;
                                $kjtime = 0==$i ? $begin_time : $end_time;
                                $this->insertNext($czid,$begin_qh,$end_qh,$kjtime,$fp_time);
                            }
                        }
                        break;
                    default:
                        continue;
                }
            }

        }
        $end = microtime(true);
        echo "<br/>---------- 运行时间".($end-$start)." ----------<br/>";

    }
   
    /**
     * 生成新期数据
     */
    private function processingNew(){

        echo "<br/>---------- 开始生成下期数据processingNew ----------<br/><br/>";
        $start = microtime(true);
        $max_id_query = Db::name('kjjg_list')
            ->field('MAX(qihao),czid')
            ->group('czid')
            ->buildSql();
        $max_czid_query = Db::name('kjjg_list')
            ->field('czid,kjjg,qihao,jztime')
            ->where("(qihao,czid) IN({$max_id_query})")
            ->buildSql();

        $periods_query = Db::name('time')
            ->field('czid,MIN(jztime) as last_time,MIN(qihao) as num')
            ->where('jztime', '>=', date('H:i:s', $this->time))
            ->group('czid')
            ->buildSql();
        $cp_list = Db::name('caipai_list')->alias('cl')
            ->join("{$max_czid_query} klq", 'cl.id=klq.czid','LEFT')
            ->join("{$periods_query} tq", 'cl.id=tq.czid','LEFT')
            ->order('cl.id', 'ASC')
            ->column('klq.kjjg,klq.qihao,klq.jztime,tq.last_time,tq.num,cl.cp_fp_time', 'cl.id');
        /*todo*/
        $time_min = Db::name('time')->field('MIN(qihao),czid')->group('czid')->column('qihao as num,jztime','czid');
        $time_min_xyft = Db::name('time')->where(['czid'=>61])->field('qihao,jztime')->order("jztime ASC")->find();
        $time_min_xj11x5 = Db::name('time')->where(['czid'=>2])->field('qihao,jztime')->order("jztime ASC")->find();

        $xyft_time_qh = Db::name('time')->where(['czid'=>61])->column("jztime,qihao");
        $xj11x5_time_qh = Db::name('time')->where(['czid'=>2])->column("jztime,qihao");

        foreach ($cp_list as $cl) {
            if ($cl['kjjg'] == '0' && $cl['jztime'] > $this->time) continue; //此判断很重要，防止数据生成延误或重复生成
            $qihao_new = '';
            /*todo*/
            if( empty($cl['last_time']) || empty($cl['num']) ){
                if( 61==intval($cl['id']) ){//幸运飞艇
                    $kjtime['jztime'] = $time_min_xyft['jztime'];
                    $kjtime['qihao']  =$time_min_xyft['qihao'];
                }elseif( 2==intval($cl['id']) ){//幸运飞艇
                    $kjtime['jztime'] = $time_min_xj11x5['jztime'];
                    $kjtime['qihao']  =$time_min_xj11x5['qihao'];
                }elseif( 1==intval($cl['id']) ){//重庆时时彩
                    $kjtime['jztime'] = '00:00:00';
                    $kjtime['qihao']  = '120';
                }else{
                    $kjtime['jztime'] = $time_min[$cl['id']]['jztime'];
                    $kjtime['qihao']  = $time_min[$cl['id']]['num'];
                }
                $sz_time = strtotime(date("Y-m-d",strtotime("+1 day")) . ' ' . $kjtime['jztime']);
            }else{
                $kjtime['jztime'] = $cl['last_time'];
                $kjtime['qihao'] = $cl['num'];
                if( 61==intval($cl['id']) ){
                    $kjtime['qihao'] = $xyft_time_qh[$kjtime['jztime']];
                }elseif( 2==intval($cl['id']) ){
                    $kjtime['qihao'] = $xj11x5_time_qh[$kjtime['jztime']];
                }
                $sz_time = strtotime(date('Y-m-d') . ' ' . $kjtime['jztime']);
            }
            //将当期期号存入redis，生成新期后此期便作为上一期，便于后续操作
            $this->redis->set("secend_{$cl['id']}", "{$cl['qihao']}");
            switch ( intval($cl['id']) ) {
                case 1://重庆时时彩
                    if ($kjtime['qihao'] < 10) $kjtime['qihao'] = '00' . $kjtime['qihao'];
                    if ($kjtime['qihao'] >= 10 && $kjtime['qihao'] < 100) $kjtime['qihao'] = '0' . $kjtime['qihao'];
                    $qihao_new = (120==intval($kjtime['qihao'])) ? date('Ymd', $this->time).$kjtime['qihao'] : date('Ymd', $sz_time).$kjtime['qihao'];
                    $sz_time = floor($sz_time)-floor($cl['cp_fp_time']);
                    $this->insertNew($cl['id'], $qihao_new, $sz_time, '官方彩无预设');
                    break;
                case 36://安徽快三
                case 39://甘肃快3  gsk3
                case 40://广西快3  gxk3
                case 41://贵州快3  gzk3
                case 43://湖北快3  hubk3
//                case 46://吉林快3
                case 47://上海快3  shk3
                case 44://江苏快三
                case 8: //天津时时彩彩
                case 73: //五分六合彩
                    if ($kjtime['qihao'] < 10) $kjtime['qihao'] = '00' . $kjtime['qihao'];
                    if ($kjtime['qihao'] >= 10 && $kjtime['qihao'] < 100) $kjtime['qihao'] = '0' . $kjtime['qihao'];
                    $qihao_new = date('Ymd', $sz_time) . $kjtime['qihao'];
                    $sz_time = floor($sz_time)-floor($cl['cp_fp_time']);
                    $this->insertNew($cl['id'], $qihao_new, $sz_time, '官方彩无预设');
                    break;
                case 4: //北京赛车
                case 5: //排列三
                case 10: //PC蛋蛋
                case 7: //上海时时乐
                    $qihao_tmp = $cl['qihao'] + 1;
                    if (strlen($qihao_tmp) == strlen($cl['qihao'])) {
                        $qihao_new = $qihao_tmp;
                    } else {
                        $qihao_new = '0' . $qihao_tmp;
                    }
                    if( 4==intval($cl['id']) ) file_put_contents("bjsc_new.txt",$qihao_new."===".$sz_time.'==='.date('Y-m-d H:i:s',$sz_time),FILE_APPEND);
                    $sz_time = floor($sz_time)-floor($cl['cp_fp_time']);
                    $this->insertNew($cl['id'], $qihao_new, $sz_time, '官方彩无预设');
                    break;
                case 9: //香港六合彩
                    if( time() < strtotime(date('Y-m-d 21:30:00')) ){
                        $calc_time = strtotime('-1 day');
                    }else{
                        $calc_time = time();
                    }
                    $week = date("w", $calc_time);
                    if ($week == '2' || $week == '4' || $week == '0') {   //星期2,4 日+2天
                        $sz_time = strtotime(date('Y-m-d', $calc_time + 2 * 24 * 3600) . ' ' . $kjtime['jztime']);
                    }

                    if ($week == '6' ) {   //星期6+3天
                        if((11==intval(date('m',$calc_time)) && 10==intval(date('d',$calc_time))) || (12==intval(date('m',$calc_time)) && 29==intval(date('d',$calc_time)))){
                            $sz_time = strtotime(date('Y-m-d', $calc_time + 1 * 24 * 3600) . ' ' . $kjtime['jztime']);
                        }else{
                            $sz_time = strtotime(date('Y-m-d', $calc_time + 3 * 24 * 3600) . ' ' . $kjtime['jztime']);
                        }
                    }
                    if ($week == '1' || $week == '3' || $week == '5') {   //星期1,3,5+1天
                        $sz_time = strtotime(date('Y-m-d', $calc_time + 1 * 24 * 3600) . ' ' . $kjtime['jztime']);
                    }

                    //11月10日，12月29日时延后一天
                    $month = date('m',$sz_time);
                    $day = date('d',$sz_time);
                    if( (11==intval($month) && 10==intval($day)) || (12==intval($month) && 29==intval($day)) ){
                        $sz_time += 24*60*60;
                    }

                    $qihao_tmp = $cl['qihao'] + 1;
                    if (strlen($qihao_tmp) == strlen($cl['qihao'])) {
                        $qihao_new = $qihao_tmp;
                    } else {
                        $qihao_new = '0' . $qihao_tmp;
                    }
                    $sz_time = floor($sz_time)-floor($cl['cp_fp_time']);
                    $this->insertNew($cl['id'], $qihao_new, $sz_time, '官方彩无预设');
                    break;
                case 16: //广东11选5
                case 28: //山东11选5
				case 29: //上海11选5
                case 48: //上海时时乐
                case 25: //江西11选5
                    if ($kjtime['qihao'] < 10) {
                        $kjtime['qihao'] = '0' . $kjtime['qihao'];
                    }
                    $qihao_new = date('Ymd', $sz_time) . $kjtime['qihao'];
                    $sz_time = floor($sz_time)-floor($cl['cp_fp_time']);
                    $this->insertNew($cl['id'], $qihao_new, $sz_time, '官方彩无预设');
                    break;
                case 51: //七星彩
                    if( time() < strtotime(date('Y-m-d 20:30:00')) ){
                        $calc_time = strtotime('-1 day');
                    }else{
                        $calc_time = time();
                    }
                    $week = date("w", $calc_time);
                    if ($week == '3' || $week == '5' || $week == '0') {   //星期3+2天
                        $sz_time = strtotime(date('Y-m-d', $calc_time + 2 * 24 * 3600) . ' ' . $kjtime['jztime']);
                    }
                    if ($week == '2') {   //星期2+3天
                        $sz_time = strtotime(date('Y-m-d', $calc_time + 3 * 24 * 3600) . ' ' . $kjtime['jztime']);
                    }
                    if ($week == '1' || $week == '4' || $week == '6') {   //星期4,6+1天
                        $sz_time = strtotime(date('Y-m-d', $calc_time + 1 * 24 * 3600) . ' ' . $kjtime['jztime']);
                    }
                    $qihao_tmp = $cl['qihao'] + 1;
                    if (strlen($qihao_tmp) == strlen($cl['qihao'])) {
                        $qihao_new = $qihao_tmp;
                    } else {
                        $qihao_new = '0' . $qihao_tmp;
                    }
                    $sz_time = floor($sz_time)-floor($cl['cp_fp_time']);
                    $this->insertNew($cl['id'], $qihao_new, $sz_time, '官方彩无预设');
                    break;
                case 61: //幸运飞艇
                    $cut_off = strtotime(date('Y-m-d').' 04:04:00');
                    if ($this->time < $cut_off) {
                        $sztime = strtotime(date('Y-m-d', strtotime('-1 day')) . ' ' . $kjtime['jztime']);
                        $qihao_new = date('Ymd', $sztime) . $kjtime['qihao'];
                    }elseif( $this->time > strtotime(date('Y-m-d').' '.'23:59:00') ){
                        $sztime = strtotime(date('Y-m-d') . ' ' . $kjtime['jztime']);
                        $qihao_new = date('Ymd', $sztime) . $kjtime['qihao'];
                    }else{
                        if ($kjtime['qihao'] < 10) $kjtime['qihao'] = '00' . $kjtime['qihao'];
                        if ($kjtime['qihao'] >= 10 && $kjtime['qihao'] < 100) $kjtime['qihao'] = '0' . $kjtime['qihao'];
                        $qihao_new = date('Ymd', $sz_time) . $kjtime['qihao'];
                    }
                    $sz_time = floor($sz_time)-floor($cl['cp_fp_time']);
                    $this->insertNew($cl['id'], $qihao_new, $sz_time, '官方彩无预设');
                    break;
                case 2:
                    $cut_off = strtotime( date('Y-m-d').' 02:00:00' );
                    if( $this->time <= $cut_off ){
                        $sztime = strtotime(date('Y-m-d', strtotime('-1 day')) . ' ' . $kjtime['jztime']);
                        $qihao_new = date('Ymd', $sztime).str_pad($kjtime['qihao'],3,"0",STR_PAD_LEFT);
                    }else{
                        $qihao_new = date('Ymd', $sz_time) .str_pad($kjtime['qihao'],3,"0",STR_PAD_LEFT);
                    }
                    $sz_time = floor($sz_time)-floor($cl['cp_fp_time']);
                    $this->insertNew($cl['id'], $qihao_new, $sz_time, '官方彩无预设');
                    break;
            }
            //处理新期的追号
            if ($qihao_new) {
                //检查新期是否存在追号
                $trace_num = Db::name('touzhu_list_zh')->where(['czid' => $cl['id'], 'qihao' => ['<=',$qihao_new]])->select();
                if ($trace_num) {
                    foreach ($trace_num as $vt) {
                        $data = array(
                            'czid' => $vt['czid'], 'qihao' => $vt['qihao'], 'tzhm' => $vt['tzhm'], 'tzje' => $vt['tzje'], 'dzje' => $vt['dzje'],
                            'tzzs' => $vt['tzzs'], 'username' => $vt['username'], 'tzhje' => $vt['tzhje'], 'zjje' => $vt['zjje'],
                            'ifqs' => $vt['ifqs'], 'wfid' => $vt['wfid'], 'dqpl' => $vt['dqpl'], 'xzfd' => $vt['xzfd'], 'fdje' => $vt['fdje'],
                            'kjjg' => $vt['kjjg'], 'zjzs' => $vt['zjzs'], 'nbzh' => $vt['nbzh'], 'tz_time' => $vt['tz_time'],'method'=> $vt['method']
                        );
                        $data['from'] = 1==intval($vt['stop']) ? 1 : 2;
                        Db::startTrans();
                        try {
                            Db::name('touzhu_list_no')->data($data)->insert();
                            Db::name('touzhu_list_zh')->data($data)->where('id', $vt['id'])->delete();
                            Db::commit();
                            echo "{$vt['czid']} 号彩第 {$qihao_new} 期追号更新成功<br/>";
                        } catch (\Exception $e) {
                            Db::rollback();
                            echo "{$vt['czid']} 号彩第 {$qihao_new} 期追号更新失败<br/>";
                        }
                        usleep(10000);
                    }
                }
            }
            usleep(10000);
        }
        $end = microtime(true);
        echo "<br/>---------- 运行时间".($end-$start)." ----------<br/>";
        echo "<br/>---------- 生成下期数据完成 ----------";
    }
    
    /**
     * 新期写入库
     */
    private function insertNew($czid, $qihao, $jztime, $pss)
    {
        $res = Db::name('kjjg_list')->where(['czid' => $czid, 'qihao' => $qihao])->find();
        if (!$res) {
            Db::name('kjjg_list')->data(['czid' => $czid, 'qihao' => $qihao, 'jztime' => $jztime, 'kjjg' => '0', 'iftz' => 0, 'ps' => $pss])->insert();
            echo "{$czid} 号彩第 {$qihao} 期新期写入成功";
            $this->insertNewRedis($czid, $qihao, $jztime);
        }
    }
    private function insertNext($czid,$begin_qh,$end_qh,$end_time,$fp_time=0){
        $end_count = Db::name("kjjg_list")->where(['czid'=>$czid,'qihao'=>$end_qh])->count();
        if( $czid > 0 && 0 == $end_count ){
            $this->redis->set("secend_{$czid}", $begin_qh);
            Db::startTrans();
            try{
                if(!Db::name('kjjg_list')->data(['czid' => $czid, 'qihao' => $end_qh, 'jztime' => $end_time-$fp_time, 'kjjg' => '0', 'iftz' => 0, 'ps' => '官方彩无预设'])->insert()){
                    throw new Exception("{$czid} 号彩第 {$end_qh} 期新期写入失败");
                }
                echo "{$czid} 号彩第 {$end_qh} 期新期写入成功";
                $this->insertNewRedis($czid, $end_qh, $end_time-$fp_time);
                //检查新期是否存在追号
                $trace_num = Db::name('touzhu_list_zh')->where(['czid' => $czid, 'qihao' => $end_qh])->select();
                if($trace_num) {
                    foreach ($trace_num as $vt) {
                        $data = array(
                            'czid' => $vt['czid'], 'qihao' => $vt['qihao'], 'tzhm' => $vt['tzhm'], 'tzje' => $vt['tzje'], 'dzje' => $vt['dzje'],
                            'tzzs' => $vt['tzzs'], 'username' => $vt['username'], 'tzhje' => $vt['tzhje'], 'zjje' => $vt['zjje'],
                            'ifqs' => $vt['ifqs'], 'wfid' => $vt['wfid'], 'dqpl' => $vt['dqpl'], 'xzfd' => $vt['xzfd'], 'fdje' => $vt['fdje'],
                            'kjjg' => $vt['kjjg'], 'zjzs' => $vt['zjzs'], 'nbzh' => $vt['nbzh'], 'tz_time' => $vt['tz_time']
                        );
                        if( !Db::name('touzhu_list_no')->data($data)->insert() ){
                            throw new Exception("导入NO表失败！");
                        }
                        if( !Db::name('touzhu_list_zh')->data($data)->where('id', $vt['id'])->delete() ){
                            throw new Exception("清空追号表失败！");
                        }
                        echo "{$vt['czid']} 号彩第 {$end_qh} 期追号更新成功<br/>";
                        usleep(10000);
                    }
                }
                Db::commit();
            }catch (Exception $e){
                echo "{$czid} 号彩第 {$end_qh} 期新期写入失败";
                Db::rollback();
            }
        }
    }
    private function getLowerNextTime($time,$czid,$open_time){

        $sz_time = '';
        if( 9==$czid ){

            if( $time < strtotime(date('Y-m-d',$time).' 21:30:00') ){
                $calc_time = strtotime('-1 day',$time);
            }else{
                $calc_time = $time;
            }
            $week = date("w", $calc_time);
            if ($week == '2' || $week == '4' || $week == '0') {   //星期2,4 日+2天
                $sz_time = strtotime(date('Y-m-d', $calc_time + 2 * 24 * 3600) . ' ' . $open_time);
            }
            if ($week == '6') {   //星期6+3天
                if((11==intval(date('m',$calc_time)) && 10==intval(date('d',$calc_time))) || (12==intval(date('m',$calc_time)) && 29==intval(date('d',$calc_time)))){
                    $sz_time = strtotime(date('Y-m-d', $calc_time + 1 * 24 * 3600) . ' ' . $open_time);
                }else{
                    $sz_time = strtotime(date('Y-m-d', $calc_time + 3 * 24 * 3600) . ' ' . $open_time);
                }
            }
            if ($week == '1' || $week == '3' || $week == '5') {   //星期1,3,5+1天
                $sz_time = strtotime(date('Y-m-d', $calc_time + 1 * 24 * 3600) . ' ' . $open_time);
            }
            //11月10日，12月29日时延后一天
            $month = date('m',$sz_time);
            $day = date('d',$sz_time);
            if( (11==intval($month) && 10==intval($day)) || (12==intval($month) && 29==intval($day)) ){
                $sz_time += 24*60*60;
            }
        }elseif( 51==$czid ){
            if( $time < strtotime(date('Y-m-d',$time).' 20:30:00') ){
                $week = date("w", strtotime('-1 day'));
            }else{
                $week = date("w", $time);
            }
            if ($week == '3' || $week == '5' || $week == '0') {   //星期3+2天
                $sz_time = strtotime(date('Y-m-d', $time + 2 * 24 * 3600) . ' ' . $open_time);
            }
            if ($week == '2') {   //星期2+3天
                $sz_time = strtotime(date('Y-m-d', $time + 3 * 24 * 3600) . ' ' . $open_time);
            }
            if ($week == '1' || $week == '4' || $week == '6') {   //星期4,6+1天
                $sz_time = strtotime(date('Y-m-d', $time + 1 * 24 * 3600) . ' ' . $open_time);
            }
        }
        return $sz_time;
    }
    /**
     * 新期写入Redis
     */
    private function insertNewRedis($czid, $qihao, $jztime)
    {
        $this->redis->set("{$czid}", "{$qihao},{$jztime},0");
        echo " Redis写入成功<br/>";
    }

}
